#include "homeview.h"
#include <QDeclarativeEngine>
#include <QPropertyAnimation>
#include <QxtGlobalShortcut>
#include <qrect.h>
#include <QDebug>
#include <QString>
#include <QShortcut>
#include "ShellInvoke.h"
#include "displayitem.h"

HomeView::HomeView(QWidget *parent) :
    QDeclarativeView(parent)
{
    this->setObjectName(QString::fromUtf8("declarativeView"));
    this->setGeometry(QRect(10, 0, 531, 391));

    //translucid
    QPalette palette;
    palette.setColor(QPalette::Base, Qt::transparent);
    this->setPalette(palette);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setAutoFillBackground(false);

    //register
    qmlRegisterType<ShellInvoke>("ShellInvoke", 1, 0, "ShellInvoke");
    qmlRegisterType<DisplayItem>("DisplayItem", 1, 0, "DisplayItem");

    this->loadNewQml("/home/emmanuel/CatHome/qml/home/main.qml");
    this->rootContext()->setContextProperty("rootContainer", this);
    QxtGlobalShortcut* shortcut = new QxtGlobalShortcut(this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(toggleVisibility()));
    shortcut->setShortcut(QKeySequence("Ctrl+Shift+F12"));
    QShortcut* qShort = new QShortcut(QKeySequence(Qt::Key_F5), this);
    qShort->setContext(Qt::ApplicationShortcut);
    connect(qShort, SIGNAL(activated()), this, SLOT(refreshQml()) ) ;

    QShortcut* qShort2 = new QShortcut(QKeySequence(Qt::Key_Backspace), this);
    qShort2->setContext(Qt::ApplicationShortcut);
    connect(qShort2, SIGNAL(activated()), this, SLOT(previousQml())) ;

    visible=true;
}



void HomeView::refreshQml()
{

    qDebug() << "innerQMLFile: " << innerQMLFile;
    qDebug() << "qmlPathFile: " << qmlPathFile;

    this->setSource(QUrl::fromLocalFile(innerQMLFile));
    this->rootContext()->setContextProperty("rootContainer", this);
    this->show();
    //center
    QRect rect;
    rect = QApplication::desktop()->screenGeometry(-1);
    this->move (rect.center() - this->rect().center());

}

void HomeView::previousQml(){
    if(qmlPathFile.length()>0){
        innerQMLFile = qmlPathFile.last();
        qmlPathFile.removeLast();
    }
    refreshQml();
    qDebug() << "previousQml";
}

void HomeView::loadNewQml(QString sFileName){
    if(!innerQMLFile.isNull()){
        qmlPathFile << innerQMLFile;
    }
    innerQMLFile = sFileName;
    refreshQml();
}

void HomeView::toggleVisibility()
{
        mAnimation = new QPropertyAnimation(this, "geometry");
        mAnimation->setDuration(1000);
        mAnimation->setEasingCurve(QEasingCurve::InOutQuad);

        if(visible){
            this->visibleRect = new QRect(this->geometry());
            QRect invisibleRect = this->visibleRect->adjusted(0,0,0,0);
            invisibleRect.setRight(0);
            left = this->geometry().left();
            mAnimation->setEndValue(invisibleRect);
            visible=false;
        }else{
            mAnimation->setEndValue(*visibleRect);
            visible=true;
        }
        mAnimation->start();
}
